assert = require 'assert'
async = require 'async'
genericPool = require 'generic-pool'
mysql =  require 'mysql'
class DbConnection
  constructor: (option) ->
    option.driver = 'mysql' unless option.driver?
    option.mysqlCharsetNumber = 33 unless option.mysqlCharsetNumber?
    @timeout = option.timeout ? 1000
    @log = option.log ? console
    @pool = genericPool.Pool
      name: option.name ? 'db'
      create: (callback) ->
        connection = mysql.createConnection option
        connection.connect (err)->
          return callback err,connection
      destroy: (conn) -> conn.destroy()
      max: option.pool * 2
      idleTimeoutMillis: option.idleTimeoutMillis

  connect: (command, callback) ->
    assert.ok typeof(command) is 'function' and typeof(callback) is 'function'
    @pool.acquire (err, client) =>
      return callback err, null if err
      command client, (err, result) =>
        @pool.release client
        callback err, result

  runSqlList: (list,callback) ->
    ops = (@runSqlFun i.sql, (i.args ? []) for i in list)
    async.series ops, callback

  runSqlFun: (sql,args) ->
    (callback) => @runSql sql,args,callback

  runSql: (sql,args,callback) ->
    if callback?
      op = (conn,cb) -> conn.query sql,args,cb
    else
      callback = args
      op = (conn,cb) -> conn.query sql,cb
    @connect op, callback

  runSqlAll: (sql,args,callback) ->
    if callback?
      op = (conn,cb) -> conn.query sql,args,cb
    else
      callback = args
      op = (conn,cb) -> conn.query sql,cb
    @connect op, callback

  queryOne: (sql,args,callback) ->
    unless callback?
      callback = args
      args = []
    op = (conn,cb) -> conn.query sql,args,(err,result) ->
      cb err, result?[0] ? null
    @connect op, callback

  queryAll: (sql,args,callback) ->
    unless callback?
      callback = args
      args = []
    op = (conn,cb) -> conn.query sql,args,cb
    @connect op, callback

{connection} = require '../config'
option = connection[process.env['NODE_ENV']] || connection.test
option.name = 'db'
option.driver = 'mysql'
conn = new DbConnection option
module.exports = connect = conn.connect.bind(conn)
connect.runSqlList = conn.runSqlList.bind(conn)
connect.runSqlFun = conn.runSqlFun.bind(conn)
connect.runSql = conn.runSql.bind(conn)
connect.runSqlAll = conn.runSqlAll.bind(conn)
connect.queryOne = conn.queryOne.bind(conn)
connect.queryAll = conn.queryAll.bind(conn)

module.exports.DbConnection = DbConnection

PRODUCTION_CONNECTION = new DbConnection connection.production 
module.exports.PRODUCTION_CONNECTION =  PRODUCTION_CONNECTION
module.exports.escapeLike = (str) ->
  str.replace /([%_])/g,'\\$1'
